<template>
	<tabNavHeader :title="title">
		<template v-slot:left>
			<view @click="openHistory">
				<image style="width: 40rpx;height: 40rpx;" :src="leftSvg" mode=""></image>
			</view>
		</template>
		<template v-slot:right>
			<view @click="openPopup">
				<image style="width: 40rpx;height: 40rpx;" :src="rightSvg" mode=""></image>
			</view>
		</template>
	</tabNavHeader>
	<view class="body-box">
		<!-- 头部文案 -->
		<view v-if="!isNewTalks && !isHistory && !isSendMsg" class="top-text">
			<view class="title"><zero-markdown-view markdown="Hi~我是deepseek"></zero-markdown-view></view>
			<zero-markdown-view :markdown="subtitle"></zero-markdown-view>
		</view>

		<!-- 中间内容 -->
		<view class="message-box" :style="{ height: `calc(100vh - ${noMsgHeight}px) !important` }">
			<scroll-view scroll-y :scroll-top="scrollTop" @scroll="handleScroll" class="chat-list"
				:style="{ height: `calc(100vh - ${noMsgHeight}px) !important` }">
				<view v-for="(item, index) in dataSources" :key="index" class="item">
					<view :class="item.role">
						<!-- 深度思考 -->
						<view v-if="item.role === 'ASSISTANT' && item.reasoningContent" class="reasoning">
							<view>{{item.reasoningStatus ? item.reasoningStatus : '已深度思考'}}</view>
							<zero-markdown-view :markdown="item.reasoningContent"></zero-markdown-view>
						</view>
						<!-- 加载动效 -->
						<view v-if="item.thinking" class="thinking">
							<view class="loader"></view>
							<view style="color: #333;font-size: 28rpx;">思考中...</view>
						</view>
						<!-- 没有深度思考 -->
						<zero-markdown-view :markdown="item.content" ref="markdownView"></zero-markdown-view>
						<!-- 复制和再次回复 -->
						<view class="tips" v-show="item.isFinished">
							<image style="width: 28rpx;height: 28rpx;margin-right: 24rpx;" :src="copySvg" mode="" @click="copy(index)">
							</image>
							<image style="width: 28rpx;height: 28rpx;" :src="reloadSvg" mode="" @click="reload(index)"></image>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>

		<!-- 底部固定 -->
		<view class="uni-popup-fixed" :style="{ bottom: tabbarHeight + 'px' }">
			<view class="bts-box">
				<view class="bts-left">
					<view :class="isSdsk ? 'btn btn-red' : 'btn'" @click="changeModel(1)">
						<image style="width: 32rpx;height: 32rpx;" :src="isSdsk ? sdskActiveSvg : sdskSvg" mode=""></image>
						<span>深度思考(R1)</span>
					</view>
		<!-- 			<view :class="isLwss ? 'btn btn-red' : 'btn'" @click="changeModel(2)">
						<image style="width: 28rpx;height: 28rpx;" :src="isLwss ? lwssActiveSvg : lwssSvg" mode=""></image>
						<span>联网搜索</span>
					</view> -->
				</view>
				<!-- <view class="bts-right">
					<uv-icon name="plus-circle" size="24" color="#999"></uv-icon>
				</view> -->
			</view>

			<view class="input-box">
				<textarea placeholder="有问题, 尽管问" v-model="prompt" @confirm="inputConfirm"></textarea>
				<view class="send" @click="inputConfirm">
					发送
				</view>
			</view>
		</view>

		<!-- 底部问题弹窗 -->
		<!-- 		<uni-popup ref="showBottom" type="bottom" border-radius="40rpx 40rpx 0 0">
			<view class="uni-popup">
				<view class="input-box">
					<input class="uni-input" focus placeholder="有问题, 尽管问" v-model="prompt" @confirm="inputConfirm" />
					<view class="send" @click="inputConfirm">
						发送
					</view>
				</view>
								<view class="bts-box">
					<view class="bts-left">
						<view :class="isSdsk ? 'btn btn-red' : 'btn'" @click="changeModel(1)">
							<svg width="14" height="14" viewBox="0 0 14 14" xmlns="http://www.w3.org/2000/svg">
								<path :fill="isSdsk ? '#f00' : ''"
									d="M0.734485 13.265C-0.132106 12.3998 -0.245505 10.92 0.468488 9.065C0.744285 8.3608 1.09008 7.6846 1.49608 7.0462L1.52408 7L1.49608 6.9538C1.08999 6.31592 0.745446 5.64088 0.467088 4.9378C-0.245505 3.08 -0.132106 1.6002 0.734485 0.7336C1.21188 0.2562 1.89787 0 2.72807 0C3.94325 0 5.43004 0.5418 6.95602 1.498L7.00222 1.526L7.04702 1.498C8.57161 0.5432 10.0584 0 11.2736 0C12.1038 0 12.7898 0.2562 13.2658 0.7336C14.131 1.6002 14.2458 3.0814 13.5318 4.9364C13.2543 5.63964 12.9102 6.31471 12.5042 6.9524L12.4748 7L12.5028 7.0448C12.9298 7.7266 13.2798 8.407 13.5318 9.0622C14.2458 10.9172 14.1324 12.3984 13.2658 13.265C12.7898 13.7424 12.1038 13.9986 11.275 13.9986C10.0584 13.9986 8.57301 13.4554 7.04702 12.5006L6.99942 12.4726L6.95462 12.5006C5.42864 13.4568 3.94185 14 2.72667 14C1.89647 14 1.21048 13.7438 0.734485 13.2664V13.265ZM12.3628 9.513C12.1915 9.07458 11.9894 8.64884 11.758 8.239L11.6936 8.127L11.6152 8.2292C10.6352 9.4976 9.497 10.6344 8.23001 11.6144L8.12781 11.6942L8.23981 11.7572C9.3556 12.383 10.4238 12.7484 11.2736 12.7484C11.7538 12.7484 12.1318 12.6308 12.3796 12.3816C12.6372 12.1254 12.7534 11.7208 12.7464 11.2336C12.7394 10.7436 12.6106 10.1556 12.3628 9.5116V9.513ZM6.95042 10.92L6.99942 10.9564L7.04982 10.92C8.54514 9.84917 9.85631 8.54224 10.932 7.0504L10.9684 7L10.932 6.951C9.85815 5.4572 8.54671 4.14952 7.04982 3.08L6.99942 3.045L6.95042 3.0814C5.45464 4.15215 4.143 5.45908 3.06686 6.951L3.03046 7L3.06686 7.0504C4.14121 8.54423 5.45312 9.8519 6.95042 10.9214V10.92ZM12.381 1.6198C12.1304 1.3706 11.7524 1.253 11.2736 1.253C10.4224 1.253 9.3556 1.617 8.23981 2.2442L8.12781 2.3072L8.23001 2.3856C9.4984 3.3656 10.6366 4.5024 11.6152 5.7708L11.6936 5.873L11.7566 5.761C11.9974 5.3312 12.2046 4.9042 12.3628 4.487C12.6106 3.8458 12.7408 3.2578 12.7464 2.7678C12.7534 2.2792 12.6372 1.876 12.381 1.6198ZM1.63608 4.4884C1.80827 4.9266 2.01127 5.3522 2.24227 5.7624L2.30667 5.873L2.38507 5.7708C3.36348 4.50224 4.5007 3.36454 5.76884 2.3856L5.87243 2.3072L5.76044 2.2442C4.64325 1.617 3.57646 1.253 2.72527 1.253C2.24507 1.253 1.86707 1.3706 1.61928 1.6198C1.36308 1.876 1.24688 2.2792 1.25388 2.7678C1.25948 3.2578 1.38968 3.8458 1.63608 4.4884ZM1.63608 9.513C1.38828 10.1556 1.25948 10.7436 1.25388 11.2336C1.24688 11.7208 1.36168 12.1254 1.61788 12.3816C1.86847 12.6308 2.24647 12.7484 2.72527 12.7484C3.57646 12.7484 4.64325 12.3844 5.75904 11.7572L5.87103 11.6942L5.76884 11.6144C4.5007 10.6355 3.36348 9.49776 2.38507 8.2292L2.30527 8.127L2.24227 8.239C2.00987 8.6492 1.80827 9.0748 1.63608 9.513Z"
									fill="#1D2129" />
							</svg>
							<span>深度思考</span>
						</view>
						<view :class="isLwss ? 'btn btn-red' : 'btn'" @click="changeModel(2)">
							<svg width="14" height="14" viewBox="0 0 14 14" xmlns="http://www.w3.org/2000/svg">
								<path :fill="isLwss ? '#f00' : ''"
									d="M3.43082 5.35294H1.26C1.10699 5.88856 1.02966 6.44295 1.03024 7C1.03024 7.57153 1.11012 8.12412 1.26082 8.64706H3.43165C3.34106 8.12 3.29494 7.57071 3.29494 7C3.29494 6.42929 3.34106 5.88 3.43165 5.35294H3.43082ZM4.26835 5.35294C4.16604 5.89595 4.11558 6.44745 4.11765 7C4.11765 7.57482 4.16706 8.12412 4.26835 8.64706H6.58823V5.35294H4.26835ZM5.47482 12.7738C4.59647 11.8397 3.95831 10.7061 3.61529 9.47059H1.56306C1.93016 10.2762 2.47144 10.9904 3.14787 11.5616C3.82431 12.1328 4.61906 12.5468 5.47482 12.7738ZM6.58823 12.7161V9.47059H4.47424C4.86129 10.7108 5.56541 11.7905 6.58823 12.7169V12.7161ZM5.47482 1.22706C4.61914 1.45393 3.82444 1.8678 3.14801 2.43885C2.47158 3.00991 1.93025 3.72391 1.56306 4.52941H3.61529C3.95807 3.29402 4.59595 2.16043 5.474 1.22624L5.47482 1.22706ZM6.58823 1.28471C5.56541 2.20871 4.86212 3.28835 4.47424 4.52941H6.58823V1.28306V1.28471ZM10.5692 5.35294C10.6598 5.88 10.7059 6.42929 10.7059 7C10.7059 7.57071 10.6598 8.12 10.5692 8.64706H12.7408C12.8907 8.12412 12.9706 7.57153 12.9706 7C12.9706 6.42847 12.8907 5.87588 12.74 5.35294H10.5692ZM9.73165 5.35294H7.41176V8.64706H9.73165C9.83212 8.12412 9.88235 7.57482 9.88235 7C9.88235 6.42518 9.83294 5.87588 9.73165 5.35294ZM8.52518 12.7738C9.38094 12.5468 10.1757 12.1328 10.8521 11.5616C11.5286 10.9904 12.0698 10.2762 12.4369 9.47059H10.3847C10.0419 10.706 9.40405 11.8396 8.526 12.7738H8.52518ZM7.41176 12.7161C8.43459 11.7905 9.13788 10.7108 9.52577 9.47059H7.41176V12.7169V12.7161ZM8.52518 1.22706C9.40341 2.16093 10.0416 3.29423 10.3847 4.52941H12.4378C12.0707 3.72376 11.5294 3.00959 10.8529 2.43839C10.1765 1.86719 9.38176 1.45319 8.526 1.22624L8.52518 1.22706ZM7.41176 1.28471V4.52941H9.52577C9.13871 3.28918 8.43459 2.20953 7.41176 1.28306V1.28471ZM7 14C5.14349 14 3.36301 13.2625 2.05025 11.9497C0.737498 10.637 0 8.85652 0 7C0 5.14349 0.737498 3.36301 2.05025 2.05025C3.36301 0.737498 5.14349 0 7 0C8.85652 0 10.637 0.737498 11.9497 2.05025C13.2625 3.36301 14 5.14349 14 7C14 8.85652 13.2625 10.637 11.9497 11.9497C10.637 13.2625 8.85652 14 7 14Z"
									fill="#1D2129" />
							</svg>
							<span>联网搜索</span>
						</view>
					</view>
					<view class="bts-right">
						<uv-icon name="plus-circle" size="24" color="#999"></uv-icon>
					</view>
				</view>
			</view>
		</uni-popup> -->

		<!-- 左侧抽屉 -->
		<uni-drawer ref="showLeft" mode="left" width="300">
			<view class="uni-drawer">
				<scroll-view class="scroll-view" style="height: 100%;" scroll-y="true" show-scrollbar="true"
					@scrolltolower="loadHistory(2)">
					<view class="con" v-for="(item,index) in classifiedData" :key="index">
						<view v-if="item.list.length > 0" class="date">{{item.title}}</view>
						<view @click="clickHistory(index, item2, index2)" v-for="(item2, index2) in item.list"
							:class="item2.isActive ? 'row-active row1' : 'row row1'">
							<view class="title">{{item2.title}}</view>
							<view class="del" @click.stop="deleteChat(1, item2.deepseekId)">
								<uv-icon name="trash" color="#666" size="16"></uv-icon>
							</view>
						</view>
					</view>
					<!-- 加载更多提示 -->
					<uv-load-more :status="loadStatus" :line="true" />
				</scroll-view>
				<!-- 删除所有历史对话 -->
				<view class="btm-box" v-if="historyList.length > 0">
					<view class="del" @click="deleteChat(2)">
						删除所有历史对话
					</view>
				</view>
			</view>
		</uni-drawer>

	</view>
	<!-- 自定义 tabBar -->
	<custom-tabbar :currentIndex="2" :isNew="false" ref="tabBars" />
</template>

<script setup>
	import CustomTabbar from '@/components/customTabbar/custom-tabbar.vue';
	import leftSvg from '@/static/icon/deepseek/left.svg'
	import rightSvg from '@/static/icon/deepseek/right.svg'
	import sdskActiveSvg from '@/static/icon/deepseek/sdsk_active.svg'
	import sdskSvg from '@/static/icon/deepseek/sdsk.svg'
	import lwssActiveSvg from '@/static/icon/deepseek/lwss_active.svg'
	import lwssSvg from '@/static/icon/deepseek/lwss.svg'
	import copySvg from '@/static/icon/deepseek/copy.svg'
	import reloadSvg from '@/static/icon/deepseek/reload.svg'
	import {
		onLoad,
		onShow,
		onHide,
		onUnload
	} from '@dcloudio/uni-app'
	import tabNavHeader from '@/components/tabNavHeader/tabNavHeader.vue'
	import {
		ref,
		reactive,
		computed,
		watch,
		nextTick
	} from 'vue'
	import {
		chatCompletionsApi,
		chatListApi,
		delSinglechatListApi,
		delAllchatListApi
	} from "@/api/chat";
	import {
		handleStreamResponse
	} from "./hooks/useReadStream";
	import {
		getUserProfile
	} from '@/api/system/user'
	import store from '@/store/index'
	import config from '@/config'
	import {
		getToken
	} from '@/utils/auth'
	import deepseek from '@/components/deepseek.vue'
	// 引入自定义头部导航栏相关信息
	import {
		getStatusBarHeight,
		getTitleBarHeight,
		getNavBarHeight,
	} from '@/utils/system.js'

	const currentIndex = ref(2)
	// let controller = new AbortController();
	const subtitle = ref('叮咚！您的全能小助手就位~既能一本正经聊学术，也能天马行空编故事，电量满格随时待命！现在开始我们的智慧之旅吧！')
	const title = ref('Deepseek')
	const loading = ref(false); //是否思考中
	const dataSources = ref([]) // 对话信息
	const showLeft = ref(null) // 左侧抽屉
	// const showBottom = ref(null) // 底部弹出层
	const isSdsk = ref(false) // 是否是深度思考
	const isLwss = ref(false) // 是否是联网搜索
	const prompt = ref('') // 输入框内容
	const isNewTalks = ref(false) // 是否是新对话
	const isSendMsg = ref(false) // 是否有发送消息 判断打开历史列表时更新列表
	const historyList = ref([]) // 历史记录
	const classifiedData = ref([]) // 分类的历史记录
	const isHistory = ref(false) // 是否是历史记录
	const loadStatus = ref('') // 历史列表加载状态
	const userId = ref('')
	const historyParams = ref({
		pageNum: 1,
		pageSize: 20,
		userId: ''
	}) // 历史记录 参数
	const scrollTop = ref(0)
	const tabBars = ref('') // tabbar组件名
	const tabbarHeight = ref(null) // tabbarHeight高度
	const noMsgHeight = ref(0) // 除了对话盒子其他可视区域的高度 (用来获取对话列表可视区域高度)
	const msgClientHeight = ref(0) // 对话盒子可视区域的高度 
	const isAutoScroll = ref(true) // 是否自动滚动到底部
	const lastScrollTop = ref(0) // 记录上一次滚动位置
	const markdownView = ref(null) // 获取 zero-markdown-view 的 DOM 引用
	const isFinished = ref(false) // 判断回答是否结束

	onShow(() => {
		// nextTick(() => {
		// 	showBottom.value.open();
		// })
	})

	onLoad(async () => {
		uni.hideTabBar()
		nextTick(() => {
			// 获取 tabbarHeight
			uni.createSelectorQuery().in(tabBars.value)
				.select('.custom-tabbar')
				.boundingClientRect((res) => {
					tabbarHeight.value = res.height
				})
				.exec();
			// 除去对话列表 其他元素的高度
			noMsgHeight.value = getStatusBarHeight() + getTitleBarHeight() + getNavBarHeight() + tabbarHeight.value +
				150
		});
		await getUserProfileFn()
		await loadHistory(1)

		// 获取对话列表可视区域高度
		uni.createSelectorQuery().select('.chat-list').boundingClientRect(data => {
			msgClientHeight.value = data.height // // 可视区域高度
		}).exec()

	})

	const getUserProfileFn = async () => {
		let {
			code,
			data
		} = await getUserProfile()
		if (code === 200) {
			userId.value = data.userId
			historyParams.value.userId = userId.value
		}
	}

	// 打开历史记录
	const openHistory = () => {
		showLeft.value.open();
		// console.log(isSendMsg.value, 'isSendMsg.value')
		// 如果刚发送过消息 / 打开新的对话 再点击需要更新历史列表
		if (isSendMsg.value || isNewTalks.value) {
			historyParams.value.pageNum = 1
			historyList.value = []
			isHistory.value = false
			loadHistory(1)
		}
	}

	// 加载历史记录
	const loadHistory = async (type) => {
		// type 1 打开历史记录 2 滚动加载
		if (type === 2 && (loadStatus.value === 'loading' || loadStatus.value === 'nomore')) return; // 防止重复加载
		loadStatus.value = 'loading'
		const data = await chatListApi(historyParams.value)
		if (historyList.value.length < data.total) {
			historyList.value = historyList.value.concat(data.rows)

			// 如果没有点击过历史记录, 默认第一条选中
			if (!isHistory.value) {
				historyList.value.map((item, index) => {
					if (index === 0) {
						item.isActive = true
					}
				})
			}

			// 分类的历史记录
			classifiedData.value = classifyByDate(historyList.value);
			historyParams.value.pageNum += 1

			if (data.total <= historyParams.value.pageSize) {
				loadStatus.value = 'nomore'
			} else {
				loadStatus.value = 'loadmore'
			}

		} else {
			historyList.value = []
			store._mutations.setStreamId[0]('') // 没有数据清空返回的对话id
			// 分类的历史记录
			classifiedData.value = classifyByDate(historyList.value);
			loadStatus.value = 'nomore'
		}
	}

	// 时间段分类函数
	const classifyByDate = (data) => {
		const today = new Date(); // 当前时间
		today.setHours(0, 0, 0, 0); // 设置为今天的开始时间

		const yesterday = new Date(today);
		yesterday.setDate(today.getDate() - 1); // 昨天的开始时间

		const sevenDaysAgo = new Date(today);
		sevenDaysAgo.setDate(today.getDate() - 7); // 7天前的时间

		const result = [{
			title: '今天',
			list: []
		}, {
			title: '昨天',
			list: []
		}, {
			title: '7天内',
			list: []
		}, {
			title: '7天外',
			list: []
		}];

		data.forEach((item) => {
			const itemDate = new Date(item.createTime); // 将日期字符串转换为 Date 对象
			itemDate.setHours(0, 0, 0, 0); // 设置为当天的开始时间

			if (itemDate.getTime() === today.getTime()) {
				result[0].list.push(item); // 今天
			} else if (itemDate.getTime() === yesterday.getTime()) {
				result[1].list.push(item); // 昨天
			} else if (itemDate > sevenDaysAgo && itemDate < today) {
				result[2].list.push(item); // 7天内
			} else {
				result[3].list.push(item); // 7天外
			}
		});

		return result;
	}

	const closeDrawer = () => {
		showLeft.value.close();
	}

	// 新建对话
	const openPopup = () => {
		closeDrawer() // 关闭历史记录弹出层
		title.value = 'Deepseek' // 修改标题
		store._mutations.setStreamId[0]('') // 清空对话id
		prompt.value = '' // 清空输入框数据
		isNewTalks.value = true // 新对话 清空系统介绍
		isHistory.value = false // 不是历史记录
		dataSources.value = [] // 对话列表清空
		// showBottom.value.open();
	}

	// const closePopup = () => {
	// 	prompt.value = ''
	// 	// showBottom.value.close();
	// }

	// 选择对应模板
	const changeModel = (idx) => {
		// idx 1 深度思考 2 联网搜索
		if (idx === 1) {
			isSdsk.value = !isSdsk.value
		} else {
			isLwss.value = !isLwss.value
		}
	}

	// 点击历史记录
	const clickHistory = (idx, item, idx2) => {
		historyList.value.map(item => item.isActive = false) // 去掉列表默认选中
		classifiedData.value = classifyByDate(historyList.value); // 分类的历史记录

		classifiedData.value[idx].list[idx2].isActive = true // 选中样式添加
		dataSources.value = JSON.parse(item.records).splice(1) // 去掉默认第一项
		dataSources.value.map(item=>{
			if(item.role === 'ASSISTANT'){
				item.isFinished = true
			}
		})
		store._mutations.setStreamId[0](item.deepseekId) // 存储当前对话的deepseekId
		isHistory.value = true // 去掉开始的系统介绍 并 保持左侧选中状态不变
		title.value = item.title.substring(0, 12); // 标题顶部回显
		isSendMsg.value = false // 关闭刚发送消息的状态 打开历史记录不会再次请求 
		isNewTalks.value = false
		// console.log(dataSources.value, 'dataSources')
		closeDrawer()
		// 加载完成后，滚动到最下方
		nextTick(() => {
			scrollToBottom()
		});
		// closePopup()
	}

	// 输入框回车事件 / 点击发送按钮
	const inputConfirm = async () => {
		let message = prompt.value;
		if (loading.value) return;
		if (!message || message.trim() === "") {
			return uni.showToast({
				title: '请输入内容',
				icon: 'none'
			})
		};
		// closePopup()
		dataSources.value.push({
			content: message,
			role: "USER",
		})
		await nextTick(() => {
			scrollToBottom()
		});

		dataSources.value.push({
			content: '',
			role: "ASSISTANT",
			thinking: true, // 加载中
			isFinished: false, // 回答还未结束
		})

		// 深度思考
		if (isSdsk.value) {
			const sdskArr = [{
				isReasoning: false, // 是否是深度思考
				reasoningStatus: '深度思考中...',
				reasoningContent: '', //深度思考内容
			}]
			dataSources.value.concat(...sdskArr)
		}

		await nextTick(() => {
			scrollToBottom()
		});

		// 后端接口请求
		const params = {
			prompt: message,
			userId: userId.value,
			id: store._state.data.deepseek.streamId,
			type: isSdsk.value ? 'deepseek-reasoner' : 'deepseek-chat',
			isNetSearch: isLwss.value ? 1 : 0
		}

		prompt.value = ''
		loading.value = true // 开始请求

		const requestTask = await uni.request({
			url: config.baseUrl + '/system/deepSeekRecords/chat', // 后端流式API地址
			method: 'POST',
			timeout: 100000,
			header: {
				'Content-Type': 'application/json',
				'Authorization': 'Bearer ' + getToken(),
			},
			data: params,
			success: (res) => {
				// 如果数据是SSE格式，需要解析
				const lines = res.data.split('\n');
				lines.forEach((line, index) => {
					// 打字机效果 延时打字
					setTimeout(() => {
						if (line.startsWith('data:')) {
							const jsonData = line.replace('data:', '').trim();
							if (jsonData) {
								try {
									const response = JSON.parse(jsonData);
									store._mutations.setStreamId[0](response.id) // 存储返回的对话id
									isSendMsg.value = true // 刚发送过消息 判断需要刷新历史列表
									
									// 思考信息 
									const reasoning = response.choices[0]?.delta?.reasoning_content
									if (reasoning) {
										if(dataSources.value[dataSources.value.length - 1].reasoningContent === undefined){
											dataSources.value[dataSources.value.length - 1].reasoningContent = ''
										}
										dataSources.value[dataSources.value.length - 1].reasoningContent += reasoning
										dataSources.value[dataSources.value.length - 1].isReasoning = true
										dataSources.value[dataSources.value.length - 1].reasoningStatus = '已深度思考'
										if (isAutoScroll.value) {
											scrollToBottom()
										}
									}

									// 回答信息
									const contentText = response.choices[0]?.delta?.content
									if (contentText) {
										dataSources.value[dataSources.value.length - 1].content += contentText
										dataSources.value[dataSources.value.length - 1].thinking = false
										if (isAutoScroll.value) {
											scrollToBottom()
										}
									}
									
									// 判断回答是否结束 结束显示复制和再次回答图标
									if(response.choices[0]?.finish_reason === 'stop'){
										dataSources.value[dataSources.value.length - 1].isFinished = true
										nextTick(() => {
											scrollToBottom()
										});
									}
									
									loading.value = false
								} catch (e) {
									loading.value = false
									console.error('解析JSON失败:', e);
								}
							}
						}
					}, index * 50)

				});
			},
			fail: (err) => {
				console.error('请求失败', err);
				dataSources.value[dataSources.value.length - 1].thinking = false
				if (err.errMsg === 'request:fail timeout') {
					dataSources.value[dataSources.value.length - 1].content += '请求超时'
				} else {
					dataSources.value[dataSources.value.length - 1].content += '请求失败'
				}
			},
			complete: (res) => {
				loading.value = false
				dataSources.value[dataSources.value.length - 1].thinking = false
				if (res.data.code === 500) {
					dataSources.value[dataSources.value.length - 1].content += '请求失败'
				}
				console.log('请求完成', res);
			},
		});
		console.log(requestTask, 'requestTask')
		// onConversation()
	}

	// 请求
	const onConversation = async () => {
		let message = prompt.value;
		if (loading.value) return;
		if (!message || message.trim() === "") {
			return uni.showToast({
				title: '请输入内容',
				icon: 'none'
			})
		};
		// closePopup()
		dataSources.value.push({
			content: message,
			role: "USER",
		})
		await nextTick(() => {
			scrollToBottom()
		});
		// 流式输出信号
		// let controller = new AbortController();
		// 开始发起请求
		try {
			// const paramMsg = [];
			// paramMsg.push({
			// 	role: "USER",
			// 	content: message
			// });
			// deepseek接口请求
			// const response = await chatCompletionsApi(controller.signal, paramMsg)
			dataSources.value.push({
				content: '',
				role: "ASSISTANT",
				thinking: true, // 加载中
			})

			// 深度思考
			if (isSdsk.value) {
				const sdskArr = [{
					isReasoning: false, // 是否是深度思考
					reasoningStatus: '深度思考中...',
					reasoningContent: '', //深度思考内容
					reasoning: '' // 思考信息
				}]
				dataSources.value.concat(...sdskArr)
			}

			await nextTick(() => {
				scrollToBottom()
			});

			// 后端接口请求
			const params = {
				prompt: message,
				userId: userId.value,
				id: store._state.data.deepseek.streamId,
				type: 'deepseek-chat'
			}

			// 深度思考
			if (isSdsk.value) {
				params.type = 'deepseek-reasoner'
			}


			loading.value = true // 开始请求
			// const response = await chatCompletionsApi(controller.signal, params)
			const response = await chatCompletionsApi(params)
			// 		// 如果数据是SSE格式，需要解析
			const lines = response.data.split('\n');
			lines.forEach((line) => {
				if (line.startsWith('data:')) {
					const jsonData = line.replace('data:', '').trim();
					if (jsonData) {
						try {
							const response = JSON.parse(jsonData);
							const contentText = response.choices[0]?.delta?.content

							store._mutations.setStreamId[0](response.id) // 存储返回的对话id
							isSendMsg.value = true // 刚发送过消息 判断需要刷新历史列表
							prompt.value = ''
							// console.log(contentText, "contentTextcontentText")

							if (contentText) {
								dataSources.value[dataSources.value.length - 1].content += contentText
								dataSources.value[dataSources.value.length - 1].thinking = false
								scrollToBottom()
							}

							// 思考信息
							const reasoning = response.choices[0].delta.reasoning_content;
							// console.log(reasoning, 'reasoningreasoning')
							if (reasoning) {
								dataSources.value[dataSources.value.length - 1].reasoningContent += reasoning
								dataSources.value[dataSources.value.length - 1].isReasoning = true
								dataSources.value[dataSources.value.length - 1].reasoningStatus = '已深度思考'
								scrollToBottom()
							}
						} catch (e) {
							console.error('解析JSON失败:', e);
						}
					}
				}
			});

			// handleStreamResponse h5 fetch请求使用
			// await handleStreamResponse(response, (jsonData) => {
			// 	const contentText = jsonData.choices[0]?.delta?.content

			// 	store._mutations.setStreamId[0](jsonData.id) // 存储返回的对话id
			// 	isSendMsg.value = true // 刚发送过消息 判断需要刷新历史列表
			// 	prompt.value = ''
			// 	// console.log(contentText, "contentTextcontentText")

			// 	if (contentText) {
			// 		dataSources.value[dataSources.value.length - 1].content += contentText
			// 		dataSources.value[dataSources.value.length - 1].thinking = false
			// 		scrollToBottom()
			// 	}

			// 	// 思考信息
			// 	const reasoning = jsonData.choices[0].delta.reasoning_content;
			// 	// console.log(reasoning, 'reasoningreasoning')
			// 	if (reasoning) {
			// 		dataSources.value[dataSources.value.length - 1].reasoningContent += reasoning
			// 		dataSources.value[dataSources.value.length - 1].isReasoning = true
			// 		dataSources.value[dataSources.value.length - 1].reasoningStatus = '已深度思考'
			// 		scrollToBottom()
			// 	}
			// });
			loading.value = false
			console.log("Stream ended")
		} catch (error) {
			console.log(error, 'error')
			loading.value = false
			// if (error instanceof DOMException && error.name === "AbortError") {
			// 	console.log('用户手动中断')
			// 	dataSources.value[dataSources.value.length - 1].content = "\n\n用户手动中断。"
			// 	dataSources.value[dataSources.value.length - 1].thinking = false
			// } else {
			uni.showToast({
				title: '服务器异常，请稍后再试',
				icon: 'none'
			})
			// }

		}
	}

	// 删除对话
	const deleteChat = async (type, deepseekId) => {
		// type 1 删除单个 2 删除全部
		console.log(type, deepseekId, 'type, deepseekId')
		if (type === 1) {
			uni.showModal({
				title: '删除',
				content: '确定要删除当前对话吗?',
				success: async (res) => {
					if (res.confirm) {
						const params = {
							deepseekId
						}
						const res = await delSinglechatListApi(params)
						if (res.code === 200) {
							historyParams.value.pageNum = 1
							historyList.value = []
							isHistory.value = false
							isNewTalks.value = false
							loadHistory(1)
							uni.showToast({
								title: '删除成功',
								icon: 'none'
							})
						}
					}
				}
			});
		} else {
			uni.showModal({
				title: '删除',
				content: '确定要删除全部对话吗?',
				success: async (res) => {
					if (res.confirm) {
						const params = {
							userId: userId.value
						}
						const res = await delAllchatListApi(params)
						if (res.code === 200) {
							historyParams.value.pageNum = 1
							historyList.value = []
							isHistory.value = false
							isNewTalks.value = false
							dataSources.value = []
							store._mutations.setStreamId[0]('') // 去掉存储的deepseekId
							loadHistory(1)
							uni.showToast({
								title: '删除成功',
								icon: 'none'
							})
						}
					}
				}
			});
		}
	}

	// 复制
	const copy = (index) => {
		// 获取 zero-markdown-view 渲染后的文本内容
		const textContent = markdownView.value[index].html;
		// 使用 uniapp 的 API 复制内容
		uni.setClipboardData({
			data: textContent,
			success: () => {
				uni.showToast({
					title: '内容已复制到剪贴板',
					icon: 'none',
				});
			},
			fail: (err) => {
				console.error('复制失败:', err);
				uni.showToast({
					title: '复制失败',
					icon: 'none',
				});
			},
		});
	}

	// 重新请求
	const reload = (index) => {
		prompt.value = dataSources.value[index - 1].content
		inputConfirm()
	}

	// 监听滚动事件
	const handleScroll = (event) => {
		const scrollTop = event.detail.scrollTop;
		// 判断用户是上滑还是下滑
		if (scrollTop < lastScrollTop.value) {
			// 用户上滑，暂停自动滚动
			isAutoScroll.value = false;
		} else if (scrollTop > lastScrollTop.value) {
			// 用户下滑
			const scrollHeight = event.detail.scrollHeight; // 内容总高度
			// 判断是否滑动到底部 继续滚动
			if (scrollHeight - (scrollTop + msgClientHeight.value) < 50) {
				isAutoScroll.value = true;
			}
		}

		// 更新上一次滚动位置
		lastScrollTop.value = scrollTop;
	}

	// 滚动到底部
	const scrollToBottom = () => {
		uni.createSelectorQuery().selectAll('.item').boundingClientRect(data => {
			scrollTop.value = data.reduce((sum, e) => sum + Number(e.height || 0), 0)
		}).exec()
	}

	onHide(() => {
		console.log("onHide");
		// if (loading.value) controller.abort();
	});

	onUnload(() => {
		console.log("onUnload");
		// if (loading.value) controller.abort();
	});
</script>

<style>
	page {
		background-color: #fff;
	}
</style>
<style lang="scss" scoped>
	@import '/static/style/index.scss';

	textarea {
		max-height: 200rpx;
	}

	.zero-markdown-view {
		padding: 0;
		text-align: left;
		font-family: "Arial", "Microsoft YaHei", sans-serif;
		/* 使用支持中文的字体 */
	}

	.loading-text {
		text-align: center;
		padding: 10px;
		color: #888;
	}

	.loader {
		width: 20rpx;
		aspect-ratio: 1;
		border-radius: 50%;
		margin-right: 10rpx;
		border: 4rpx solid #514b82;
		animation:
			l20-1 0.8s infinite linear alternate,
			l20-2 1.6s infinite linear;
	}

	@keyframes l20-1 {
		0% {
			clip-path: polygon(50% 50%, 0 0, 50% 0%, 50% 0%, 50% 0%, 50% 0%, 50% 0%)
		}

		12.5% {
			clip-path: polygon(50% 50%, 0 0, 50% 0%, 100% 0%, 100% 0%, 100% 0%, 100% 0%)
		}

		25% {
			clip-path: polygon(50% 50%, 0 0, 50% 0%, 100% 0%, 100% 100%, 100% 100%, 100% 100%)
		}

		50% {
			clip-path: polygon(50% 50%, 0 0, 50% 0%, 100% 0%, 100% 100%, 50% 100%, 0% 100%)
		}

		62.5% {
			clip-path: polygon(50% 50%, 100% 0, 100% 0%, 100% 0%, 100% 100%, 50% 100%, 0% 100%)
		}

		75% {
			clip-path: polygon(50% 50%, 100% 100%, 100% 100%, 100% 100%, 100% 100%, 50% 100%, 0% 100%)
		}

		100% {
			clip-path: polygon(50% 50%, 50% 100%, 50% 100%, 50% 100%, 50% 100%, 50% 100%, 0% 100%)
		}
	}

	@keyframes l20-2 {
		0% {
			transform: scaleY(1) rotate(0deg)
		}

		49.99% {
			transform: scaleY(1) rotate(135deg)
		}

		50% {
			transform: scaleY(-1) rotate(0deg)
		}

		100% {
			transform: scaleY(-1) rotate(-135deg)
		}
	}

	.body-box {
		padding: 0 40rpx;

		.top-text {
			color: #1d2129;
			padding-bottom: 20rpx;
			border-bottom: 2rpx dotted #999;

			.title {
				font-size: 48rpx;
				font-weight: bold;
			}

			.subtitle {
				font-size: 36rpx;
			}
		}

		.message-box {
			// height: calc(100vh - 520rpx);
			margin-bottom: 10px;
			border-radius: 5px;
			max-width: 100%;
			padding-top: 20rpx;


			.chat-list {
				// height: calc(100vh - 520rpx);
			}

			.item:nth-child(odd) {
				text-align: right;
			}

			.item {
				word-break: break-all;
			}
			
			.tips{
				height: 60rpx;
			}

			.thinking {
				display: flex;
				align-items: center;

				.text {
					text-align: justify;
					line-height: 32rpx;
					font-size: 28rpx;
					color: #333;
				}
			}

			.reasoning {
				border-left: 1rpx solid #86909C;
				padding-left: 20rpx;
				margin-bottom: 20rpx;

				view {
					text-align: justify;
					line-height: 28rpx;
					font-size: 24rpx;
					color: #86909C;
				}
			}

			.USER {
				max-width: 80%;
				display: inline-block;
				background-color: #F7F8FA;
				padding: 0 16rpx;
				margin-left: auto;
				border-radius: 16rpx;
				margin-bottom: 20rpx;
			}

			.ASSISTANT {
				margin-right: auto;
				margin-bottom: 20rpx;
			}

			.sender {
				font-weight: bold;
				margin-right: 5px;
			}
		}

		.uni-popup-fixed {
			width: 100%;
			position: fixed;
			left: 0;
			box-shadow: 0 -20rpx 60rpx 0 #3f3f3f1a;
			background-color: #fff;
			border-radius: 40rpx 40rpx 0 0;
			padding: 40rpx;
			height: 300rpx;

			.input-box {
				display: flex;
				align-items: center;
				justify-content: space-between;

				.uni-input {
					flex: 1;
				}

				.send {
					width: 120rpx;
					height: 60rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					color: #fff;
					background-color: #165DFF;
					border-radius: 64rpx;
				}
			}
		}

		.uni-popup {
			height: 300rpx;
			background-color: #fff;
			border-radius: 40rpx 40rpx 0 0;
			padding: 40rpx;

			.input-box {
				display: flex;
				align-items: center;
				justify-content: space-between;

				.uni-input {
					flex: 1;
				}

				.send {
					color: #fff;
					background-color: #165DFF;
					padding: 8rpx 20rpx;
					border-radius: 64rpx;
				}
			}
		}

		.bts-box {
			// margin-top: 30rpx;
			margin-bottom: 20rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;

			.bts-left {
				display: flex;
				align-items: center;

				.btn-red {
					color: #165DFF;
					background: var(---primary-1, #E8F3FF);
				}

				.btn {
					padding: 10rpx 16rpx;
					border-radius: 32px;
					border: 1px solid var(---line-1, #E5E6EB);
					display: flex;
					align-items: center;

					span {
						margin-left: 10rpx;
					}
				}

				.btn:first-child {
					margin-right: 20rpx;
				}
			}

			.bts-right {
				cursor: pointer;
				// width: 56rpx;
				// height: 56rpx;
				// display: flex;
				// align-items: center;
				// justify-content: center;
				// border-radius: 50%;
				// border: 1rpx solid #E5E6EB;
				// font-size: 50rpx;
				// padding-bottom: 8rpx;
			}
		}

		.uni-drawer {
			padding-top: 180rpx;
			height: 100%;
			display: flex;
			flex-direction: column;
			justify-content: space-between;

			.scroll-view {
				padding-bottom: 80rpx;

				.con {
					.date {
						padding-left: 10rpx;
						margin: 0 20rpx 24rpx 40rpx;
					}

					.row {
						margin-bottom: 24rpx;
						color: #86909C;
						margin: 0 20rpx 24rpx 40rpx;
					}

					.row1 {
						display: flex;
						align-items: center;
						justify-content: space-between;

						.title {
							width: 80%;
						}

						.del {
							display: flex;
							align-items: center;

							view {
								color: #f00;
								font-size: 22rpx;
								margin-left: 6rpx;
							}
						}
					}

					.row-active {
						background-color: #E8F3FF;
						padding: 10rpx 20rpx;
						border-radius: 16rpx;
						padding: 10rpx 20rpx;
						margin: 0 20rpx 24rpx 20rpx;

						.title {
							font-weight: bold;
						}
					}
				}
			}

			.btm-box {
				width: 100%;
				height: 120rpx;
				position: fixed;
				bottom: 20rpx;
				padding: 30rpx;
				background-color: #fff;

				.del {
					color: #165DFF;
					border: 1rpx solid #E5E6EB;
					padding: 16rpx 20rpx;
					border-radius: 20rpx;
				}
			}
		}
	}
</style>